{% extends "master.html" %}
{% block subtitle %} - 零售管理 - 零售开单{% endblock %}
{% block extJS %}
<script type="text/javascript" src="{{url_for('static', filename='js/jquery.inlines.min.js')}}"></script>
<script type="text/javascript" src="{{url_for('static', filename='js/numeric.js')}}"></script>
<script>
$(function() {
    initInlinesForm('#product_set-group tbody tr', 'product_set', '', [reset_fields])
    $('#query_product').typeahead({
        source: function (query, process) {
            param = {}
            param[$('#query_type').val()] = query
            return $.getJSON("{{url_for('.view', action='searchPdt')}}", param, function (data) {
                var products = [];
                var pdt_nos = get_item_nos();
                for(var i=0;i<data.products.length;i++){
                    var pdt = data.products[i]
                    var pdt_no = pdt.no
                    if(pdt_nos.indexOf(pdt_no)==-1)
                        products.push(pdt_no+'-'+pdt.name)
                }
                return process(products);
            });
        },
        updater:function (item) {
            return item;
        }
    });
    $('#query_member').typeahead({
        source: function (query, process) {
            return $.getJSON("{{url_for('bpMem.view', action='searchMem')}}", {no: query}, function (data) {
                return process(data.members);
            });
        },
        updater:function (item) {
            return item;
        }
    });
    $('#query_product').keydown(function(event) {
        if (event.which == 13) {
            add_product()
            $(this).val('')
            event.preventDefault();
        }
    }).blur(function(){
        setTimeout('add_product()', 200)
    });
    $('#val-so_payAmount').blur(function(){
        cal_refund()
    });
    $('.val-pdt_qtys').live('blur', function(){
        if(parseInt($(this).val())>parseInt($(this).next().val())){
            alert('商品数量不能超过库存！')
            $(this).val('')
        }
    })
    $('.val-pdt_price, .val-pdt_priceDiscount').live('blur', function(){
        var tr = $(this).parent().parent()
        var pPrice = $('.val-pdt_pPrice', tr).val()
        var price = $('.val-pdt_price', tr).val()
        var priceDiscount = $('.val-pdt_priceDiscount', tr).val()
        var realPrice = Math.ceil(parseFloat(price) * parseFloat(priceDiscount))/100
        if(realPrice<parseFloat(pPrice))
            alert('此商品售价低于采购价格：'+pPrice+' 元!')
    });
    $('.val-pdt_qtys, .val-pdt_price, .val-pdt_priceDiscount, .val-pdt_fee, .val-pdt_feeDiscount').live('blur', function(){
        cal_price($(this).parent().parent())
    });
    if('{{ fromAction }}'=='add'){
        $('#so-paytermID > option').each(function(){
            if($(this).text()=='现金')
                $(this).attr('selected', true);
            else
                $(this).attr('selected', false);
        })
    }
    reset_fields()
})
function reset_fields(){
    $('.nf-num, .nf-money, nf-float').numeric()
}
function add_product(){
    var flag_pdt = false;
    var flag_item = false;
    var item_no = $('#query_product').val().split('-')[0]
    var product_no = item_no.substring(0, 17)
    var pdt_nos = get_product_nos();
    for(var i=0;i<pdt_nos.length;i++){
        if(pdt_nos[i].toLowerCase()==product_no.toLowerCase())
            flag_pdt = true;
    }
    var item_nos = get_item_nos();
    for(var i=0;i<item_nos.length;i++){
        if(item_nos[i].toLowerCase()==item_no.toLowerCase())
            flag_item = true;
    }
    if(!flag_item){
        $.getJSON("{{url_for('.view', action='getPdt')}}", {no: item_no}, function (data) {
            var item = data.item
            var pdt = data.product
            var ivts = data.shopIvtPdts
            if(item){
                if(flag_pdt){
                    var qty_div = $('.txt-pdt_qtys-'+pdt.id+'-'+item.ivtID)
                    var no_size = $('.val-pdt_itemNOs', qty_div).size() + 1
                    $('.val-pdt_qtys' , qty_div).val(no_size)
                    cal_price(qty_div.parent().parent())
                    $('.dropdown-toggle', qty_div).html(no_size+"&nbsp;<span class='caret'></span>")
                    $('.dropdown-menu' , qty_div).append("<li>&nbsp;"+item.no+"<input type='hidden' class='val-pdt_itemNOs' value='"+item.no+"'/></li>")
                }else{
                    if(!$('.blank-form').hasClass('none'))
                        $('.blank-form').addClass('none')
                    $('.add-row a').click()
                    var trs_product = $('#product_set-group tbody tr')
                    var last_tr_product = trs_product[trs_product.length-3]

                    var names = $('.val-pdt_id', last_tr_product).attr('name').split('-')
                    names[2] = ''
                    var qty_html = ''
                    for(var i=0;i<ivts.length;i++){
                        qty_html += "<div class='txt-pdt_qtys-"+pdt.id+"-"+ivts[i].id+"'>"
                        if(item.ivtID==ivts[i].id){
                            qty_html += "<input type='hidden' class='val-pdt_qtys' value='1'/>\
                                <div class='btn-group'>\
                                    <a class='btn dropdown-toggle' data-toggle='dropdown' href='#'>\
                                        1&nbsp;<span class='caret'></span>\
                                    </a>\
                                    <ul class='dropdown-menu'>\
                                        <li>&nbsp;相关的商品个体</li>\
                                        <li class='divider'></li>\
                                        <li>\
                                            &nbsp;"+item.no+"\
                                            <input type='hidden' class='val-pdt_itemNOs' value='"+item.no+"'/>\
                                        </li>\
                                    </ul>\
                                </div>"
                        }else{
                            qty_html += "<input type='hidden' class='val-pdt_qtys' value='0'/>\
                                <div class='btn-group'>\
                                    <a class='btn dropdown-toggle' data-toggle='dropdown' href='#'>0\
                                        <span class='caret'></span>\
                                    </a>\
                                    <ul class='dropdown-menu'>\
                                        <li>&nbsp;相关的商品个体</li>\
                                        <li class='divider'></li>\
                                    </ul>\
                                </div>"
                        }
                        qty_html += "<input type='hidden' value='"+ivts[i].availableQty+"'/>"
                        qty_html += "<input type='hidden' class='val-pdt_ivtIDs' value='"+ivts[i].id+"'/>"
                        qty_html += ('('+ivts[i].name+',库存:'+ivts[i].availableQty+')')
                        qty_html += "</div>"
                    }
                    $('.txt-pdt_qtys', last_tr_product).append(qty_html)

                    $('.val-pdt_pPrice', last_tr_product).val(pdt.pPrice)
                    $('.val-pdt_id', last_tr_product).val(pdt.id)
                    $('.val-pdt_no', last_tr_product).val(pdt.no)
                    $('.txt-pdt_no', last_tr_product).append("\
                            <div style='float:left;width:52px;height:50px;''>\
                                <img src='"+pdt.thumbUrl+"'>\
                            </div>\
                            <div style='float:left;width:150px;'>\
                                <a href=javascript:pupupGoto('"+pdt.no+"')>"+pdt.no+"<i class='glyphicon glyphicon-eye-open'></i></a>\
                            </div><br/>"+pdt.name)
                    $('.val-pdt_price', last_tr_product).val(pdt.sPrice ? pdt.sPrice : 0)
                    $('.val-pdt_fee', last_tr_product).val(pdt.fee ? pdt.fee : 0)
                    $('.txt-pdt_action', last_tr_product).append('<a href="javascript:popupRecentPrice(\''+pdt.no+'\', \'SO\')"><i class="glyphicon glyphicon-time"></i></a>')
                    cal_price(last_tr_product)
                    reset_fields()
                }
            }
        });
    }
}
function cal_price(tr){
    var qty = 0;
    $('.val-pdt_qtys', tr).each(function(){
        qty += parseInt($(this).val() ? $(this).val() : 0)
    })
    var price = $('.val-pdt_price', tr).val()
    var priceDiscount = $('.val-pdt_priceDiscount', tr).val()
    var fee = $('.val-pdt_fee', tr).val()
    var feeDiscount = $('.val-pdt_feeDiscount', tr).val()
    var realPrice = Math.ceil(parseFloat(price) * parseFloat(priceDiscount))/100
    var realFee = Math.ceil(parseFloat(fee) * parseFloat(feeDiscount))/100
    var realAmount = Number(qty) * (parseFloat(realPrice) + parseFloat(realFee))
    var amount = Number(qty) * (parseFloat(price) + parseFloat(fee))

    $('.val-pdt_realPrice', tr).val(realPrice)
    $('.val-pdt_realFee', tr).val(realFee)
    $('.val-pdt_amount', tr).val(amount)
    $('.txt-pdt_realAmount', tr).text(realAmount)
    $('.val-pdt_realAmount', tr).val(realAmount)
    cal_amount()
}
function cal_amount(){
    var price = 0;
    $('.dynamic-form .val-pdt_amount').each(function(){
        price += parseFloat($(this).val())
    })
    $('#txt-so_amount').val(price)
    $('#val-so_amount').val(price)
    var realPrice = 0;
    $('.dynamic-form .val-pdt_realAmount').each(function(){
        realPrice += parseFloat($(this).val())
    })
    $('#txt-so_realAmount').val(realPrice)
    $('#val-so_realAmount').val(realPrice)
    cal_refund()
}
function cal_refund(){
    var refund = '';
    if($('#val-so_payAmount').val()){
        refund = Math.floor( (parseFloat($('#val-so_payAmount').val()) - parseFloat($('#val-so_realAmount').val())) * 100 ) / 100
    }
    if(refund<0){
        alert('实付不能低于商品总价！')
        $('#val-so_payAmount').val('')
        refund = ''
    }
    $('#txt-so_refundAmount').val(refund)
    $('#val-so_refundAmount').val(refund)
}
function get_product_nos() {
    var pdt_nos = []
    $('.dynamic-form .val-pdt_no').each(function(){
        pdt_nos.push($(this).val())
    })
    return pdt_nos;
}
function get_item_nos() {
    var item_nos = []
    $('.dynamic-form .val-pdt_itemNOs').each(function(){
        item_nos.push($(this).val())
    })
    return item_nos;
}
function to_save(){
    var flag = true;
    var msgs = []
    $('.required').each(function(){
        if(!$(this).val() || $(this).val()==''){
            msgs.push('请输入: '+$(this).parent().prev().text()+'')
            flag = false;
            $(this).parent().parent().removeClass('error')
            $(this).parent().parent().addClass('error')
        }
    })
    if(flag){
        $('.dynamic-form .txt-pdt_qtys').each(function(){
            var nos = []
            var qtys = []
            $('.val-pdt_qtys', this).each(function(){
                var div = $(this).parent()
                qtys.push($(this).val())
                var ivtItemNOs = []
                $('.val-pdt_itemNOs', div).each(function(){
                    ivtItemNOs.push($(this).val())
                })
                nos.push(ivtItemNOs.join(','))
            })
            var ivtIDs = []
            $('.val-pdt_ivtIDs', this).each(function(){
                ivtIDs.push($(this).val())    
            })
            var ivtQtys = []
            var qty = 0;
            for(var i=0;i<qtys.length;i++){
                var qty_val = qtys[i]
                if(qty_val && qty_val!='' && qty_val!='0'){
                    qty += parseInt(qty_val)
                    ivtQtys.push(ivtIDs[i]+','+qtys[i]+','+nos[i])
                }
            }
            $('.val-pdt_ivtQtys', this).val(ivtQtys.join('|'))
            $('.val-pdt_qty', this).val(qty)
        })
        $('#_form').submit()
    }else{
        //alertError(['{{ MSG_FIELD_REQUIRED }}'])
        alertError(msgs)
        return false;
    }
}
function toCancel(){
    redirect_alert("{{MSG_LEAVE_WITHOUT_SAVING}}", "{{url_for('.view')}}")
}
</script>
{% endblock %}
{% block main %}
<div class="container">
    <div class="row">
        <ol class="breadcrumb">
            <li><a href="{{url_for('bpRoot.view')}}">主面板</a></li>
            <li><a href="{{url_for('.view')}}">零售管理</a></li>
            <li class="active">零售开单</li>
        </ul>
    </div>
    <form method='POST' action="{{url_for('.view', action='save')}}" id='_form'>
        <input type='hidden' name='fromAction' value='{{ fromAction }}'/>
        {% if so.id %}
        <input type="hidden" name="so-id" value='{{ so.id }}'/>
        {% endif %}
        <input type="hidden" id='val-so_amount' name="so-amount" value='{{ so.amount if so.amount }}'/>
        <input type="hidden" id='val-so_realAmount' name="so-realAmount" value='{{ so.realAmount if so.realAmount else 0 }}'/>
        <input type="hidden" id='val-so_refundAmount' name="so-refundAmount" value='{{ so.refundAmount if so.refundAmount }}'/>
        <input type='hidden' name='so-shopID' value='{{ shop.id }}'/>
        <div class="row">
            <div class='btn-toolbar pull-right'>
                <button type="button" class="btn btn-success" onclick='to_save()'>保存</button>
                <a href="javascript:toCancel()" class="btn btn-inverse">取消</a>
            </div>
        </div>
    	<div class="row form-horizontal">
            <fieldset>
                <legend>零售单详情</legend>
            	<div class='form3'>
                    <div class="control-group">
        				<label class="control-label"><span style='color:red;'>*</span>付款方式</label>
        				<div class="controls">
                            {{ mymacros.select('so-paytermID', payTerms, so.paytermID, 'required') }}
        				</div>
                    </div>
                    <div class="control-group">
        				<label class="control-label">总价</label>
        				<div class="controls">
                            <input type="text" id='txt-so_amount' value='{{ so.amount if so.amount }}' disabled/>
        				</div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">折后价</label>
                        <div class="controls">
                            <input type="text" id='txt-so_realAmount' value='{{ so.realAmount if so.realAmount }}' disabled/>
                        </div>
                    </div>
                    <div class="control-group">
        				<label class="control-label"><span style='color:red;'>*</span>实付</label>
        				<div class="controls">
        				  	<input type="text" id='val-so_payAmount' name="so-payAmount" value='{{ so.payAmount if so.payAmount }}' class='required'/>
        				</div>
                    </div>
                    <div class="control-group">
        				<label class="control-label">找零</label>
        				<div class="controls">
                            <input type="text" id='txt-so_refundAmount' value='{{ so.refundAmount if so.refundAmount }}' disabled/>
        				</div>
                    </div>
               	</div>
               	<div class='form3'>
                    <div class="control-group">
                        <label class="control-label"><span style='color:red;'>*</span>销售日期</label>
                        <div class="controls">
                            <input type="text" name="soldTime" value="{{now()|fd}}" class="datepicker" class='required'/>
                        </div>
                    </div>
                    <div class="control-group">
        				<label class="control-label">分店名</label>
        				<div class="controls">
        				  	<input type="text" value="{{ shop.name }}" disabled/>
        				</div>
                    </div>
                    <div class="control-group">
        				<label class="control-label">员工</label>
        				<div class="controls">
        				  	<input type="text" value='{{ so.createBy if so.createBy else "" }}' disabled/>
        				</div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">系统编号</label>
                        <div class="controls">{{ so.no if so.no }}</div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">会员</label>
                        <div class="controls">
                            <input type='text' name='query_member' id='query_member' data-provide="typeahead" autocomplete="off" placeholder="请输入会员号" value='{{ so.member.no if so.member }}'>
                        </div>
                    </div>
    				<!--
                    <label class="control-label">销售单号</label>
                    <div class="controls">
                        <input type="text" name="so-no" value=""/>
                    </div>
    				<label class="control-label">交易号</label>
    				<div class="controls">
    				  	<input type="text" name="no" value=""/>
    				</div>
    				<label class="control-label">时间</label>
    				<div class="controls">
    				  	<input type="text" name="no" value=""/>
    				</div>
    				-->
    	        </div>
                <div class='form3'>
                    <div class="control-group">
                        <label class="control-label">用途</label>
                        <div class="controls">
                            <select name='so-usage'>
                                <option></option>
                                <option{{ ' selected' if so.usage=='嫁娶' else ''}}>嫁娶</option>
                                <option{{ ' selected' if so.usage=='生日' else ''}}>生日</option>
                                <option{{ ' selected' if so.usage=='乔迁' else ''}}>乔迁</option>
                            </select>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">备注</label>
                        <div class="controls">
                            <textarea name="so-remark">{{ so.remark if so.remark }}</textarea>
                        </div>
                    </div>
                </div>
            </fieldset>
    	</div>
	    <div class='row'>
	    	<label><strong>商品清单</strong></label>
            <select id='query_type'>
                <option value='no'>商品编号</option>
                <option value='name'>商品名称</option>
            </select>
	    	<input type='text' id='query_product' class="input-xxlarge" data-provide="typeahead" autocomplete="off" placeholder="请输入商品相关信息，回车添加商品并清空输入框信息">
            <!--
                &nbsp;&nbsp;&nbsp;&nbsp;
                <input type='button' value='批量添加商品' class='btn btn-info'/>
            -->
            {{mymacros.render_goto_popup_pdt()}}
            {{mymacros.render_recent_price_popup()}}
	    	<table class="table table-bordered" id='product_set-group'>
                <input type="hidden" name="product_set-TOTAL_FORMS" value="{{ so.dtls|length if so.dtls|length>0 else 0 }}" id="id_product_set-TOTAL_FORMS" />
                <input type="hidden" name="product_set-MAX_NUM_FORMS" id="id_product_set-MAX_NUM_FORMS" />
				<thead>
					<tr>
                        <th width='202px'>商品编号/名称</th>
						<th width='200px'>数量</th>
						<th width='130px'>单价(RMB)</th>
						<th width='130px'>手工费(RMB)</th>
                        <th width='100px'>合计(RMB)</th>
                        <th width='20px'></th>
					</tr>
				</thead>
				<tbody>
                    {% if so.dtls|length>0 %}
                    {% for dtl in so.dtls %}
                        <tr class="dynamic-form {{ loop.cycle('row1', 'row2') }}">
                            <input type='hidden' name='product_set-{{ loop.index-1 }}-id' value='{{ dtl.id }}'/>
                            <input type='hidden' name='product_set-{{ loop.index-1 }}-pdtID' class='val-pdt_id' value='{{ dtl.pdtID }}'/>
                            <input type='hidden' name='product_set-{{ loop.index-1 }}-realPrice' class='val-pdt_realPrice' value='{{ dtl.realPrice }}'/>
                            <input type='hidden' name='product_set-{{ loop.index-1 }}-realFee' class='val-pdt_realFee' value='{{ dtl.realFee }}'/>
                            <input type='hidden' name='product_set-{{ loop.index-1 }}-amount' class='val-pdt_amount' value='{{ dtl.amount }}'/>
                            <input type='hidden' name='product_set-{{ loop.index-1 }}-realAmount' class='val-pdt_realAmount' value='{{ dtl.realAmount }}'/>
                            <input type='hidden' class='val-pdt_pPrice' value='{{ dtl.pdtpPrice }}'/>
                            <input type='hidden' class='val-pdt_no' value='{{ dtl.pdtno }}'/>
                            <td class='txt-pdt_no'>
                                {{ mymacros.render_goto_popup_pdt(dtl.pdt, False) }}
                                {{ dtl.pdtname }}
                            </td>
                            <td class='txt-pdt_qtys'>
                                <input type='hidden' name='product_set-{{ loop.index-1 }}-qty' class='val-pdt_qty' value='{{ dtl.qty }}'/>
                                <input type='hidden' name='product_set-{{ loop.index-1 }}-ivtQtys' class='val-pdt_ivtQtys' value='{{ dtl.ivtQtys }}'/>
                                {% for i in dtl.shopIvtQtyObjs %}
                                <div class='txt-pdt_qtys-{{ i.pdtID }}-{{ i.ivtID }}'>
                                    <input type='hidden' class='val-pdt_qtys' value='{{ i.qty }}'/>
                                    <div class='btn-group'>
                                        <a class='btn dropdown-toggle' data-toggle='dropdown' href='#'>
                                            {{ i.qty }}&nbsp;<span class='caret'></span>
                                        </a>
                                        <ul class='dropdown-menu'>
                                            <li>&nbsp;相关的商品个体</li>
                                            <li class='divider'></li>
                                            {% for itemNO in i.itemNOs %}
                                            <li>
                                                &nbsp;{{ itemNO }}
                                                <input type='hidden' class='val-pdt_itemNOs' value='{{ itemNO }}'/>
                                            </li>
                                            {% endfor %}
                                        </ul>
                                    </div>
                                    <input type='hidden' value='product_set-{{ loop.index-1 }}-availableQty' value='{{ i.availableQty }}'/>
                                    <input type='hidden' class='val-pdt_ivtIDs' value='{{ i.ivtID }}'/>
                                    ({{ i.name }},库存:{{ i.availableQty }})
                                </div>
                                {% endfor %}
                            </td>
                            <td style='text-align:right;'>
                                <input type='text' class='input-xmini val-pdt_price nf-money' name='product_set-{{ loop.index-1 }}-price' value='{{ dtl.price }}'/>
                                <input type='text' class='input-xxmini val-pdt_priceDiscount nf-float' name='product_set-{{ loop.index-1 }}-priceDiscount' value='{{ dtl.priceDiscount }}'/>
                                <span class='red'>% 折</span>
                            </td>
                            <td style='text-align:right;'>
                                <input type='text' class='input-xmini val-pdt_fee nf-money' name='product_set-{{ loop.index-1 }}-fee' value='{{ dtl.fee }}'/>
                                <input type='text' class='input-xxmini val-pdt_feeDiscount nf-float' name='product_set-{{ loop.index-1 }}-feeDiscount' value='{{ dtl.feeDiscount }}'/>
                                <span class='red'>% 折</span>
                            </td>
                            <td class='txt-pdt_realAmount'>{{ dtl.realAmount }}</td>
                            <td class='txt-pdt_action'>
                                <div>
                                    <a class="glyphicon glyphicon-remove" href="javascript:void(0)"></a>
                                    {{ mymacros.render_recent_price_popup(dtl.pdt, False, 'SO') }}
                                </div>
                            </td>
                        </tr>
                    {% endfor %}
                    {% else %}
                    <tr class='blank-form'>
                        <td colspan='9'>暂未添加商品</td>
                    </tr>
                    {% endif %}
                    <tr class="empty-form" id="product_set-empty">
                        <td class='txt-pdt_no'>
                            <input type='hidden' name='product_set-__prefix__-pdtID' class='val-pdt_id'/>
                            <input type='hidden' name='product_set-__prefix__-realPrice' class='val-pdt_realPrice'/>
                            <input type='hidden' name='product_set-__prefix__-realFee' class='val-pdt_realFee'/>
                            <input type='hidden' name='product_set-__prefix__-amount' class='val-pdt_amount'/>
                            <input type='hidden' name='product_set-__prefix__-realAmount' class='val-pdt_realAmount'/>
                            <input type='hidden' class='val-pdt_pPrice'/>
                            <input type='hidden' class='val-pdt_no'/>
                        </td>
                        <td class='txt-pdt_qtys'>
                            <input type='hidden' name='product_set-__prefix__-qty' class='val-pdt_qty'/>
                            <input type='hidden' name='product_set-__prefix__-ivtQtys' class='val-pdt_ivtQtys'/>
                        </td>
                        <td style='text-align:right;'>
                            <input type='text' class='input-xmini val-pdt_price nf-money' name='product_set-__prefix__-price'/>
                            <input type='text' class='input-xxmini val-pdt_priceDiscount nf-float' name='product_set-__prefix__-priceDiscount' value='100'/>
                            <span class='red'>%折</span>
                        </td>
                        <td style='text-align:right;'>
                            <input type='text' class='input-xmini val-pdt_fee nf-money' name='product_set-__prefix__-fee'/>
                            <input type='text' class='input-xxmini val-pdt_feeDiscount nf-float' name='product_set-__prefix__-feeDiscount' value='100'/>
                            <span class='red'>%折</span>
                        </td>
                        <td class='txt-pdt_realAmount'></td>
                        <td class='txt-pdt_action'></td>
                    </tr>
				</tbody>
			</table>
	    </div>
	</form>
</div>
{% endblock %}